<template>
    <div class="app-container">
      <div class="filter-container">
        <el-date-picker v-model="listQuery.selectMonth" type="month" placeholder="选择月"   
        @change="jobSearch" value-format="yyyy-MM" @keyup.enter.native="handleFilter" class="filter-item">
        </el-date-picker>
        <el-select v-model="listQuery.roomId" placeholder="请选择或输入房间号" clearable class="filter-item" style="width: 200px;margin-left:10px;">
            <el-option v-for="item in roomListLoad" :autosize="{ minRows: 2, maxRows: 4}":key="item.roomId" :label="item.roomNumber" :value="item.roomNumber" />
        </el-select>
        
        <el-select v-model="listQuery.typeId" placeholder="请选择或输入费用类别" clearable class="filter-item" style="width: 200px;margin-left:10px;">
            <el-option v-for="item in typeListLoad" :autosize="{ minRows: 2, maxRows: 4}":key="item.typeName" :label="item.typeName" :value="item.typeName" />
        </el-select>
        <el-button v-waves class="filter-item" style="margin-left:10px;"type="primary" icon="el-icon-search" @click="handleFilter">
          {{ $t('table.search') }}
        </el-button>
        <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
          {{ $t('table.export') }}
        </el-button>
      </div>
      <!--表格内容-->
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
      >
        <el-table-column label="订单编号" width="60"align="center" prop="chargeRecordId" >
          <template slot-scope="{row}">
            <span>{{ row.chargeRecordId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="居民ID" prop="userId" 
        sortable="custom" align="center" width="100" :class-name="getSortClass('userId')">
          <template slot-scope="{row}">
            <span>{{ row.userId }}</span>
          </template>
        </el-table-column>

        <el-table-column label="业主名" prop="userName" 
        sortable="custom" align="center" width="100" >
          <template slot-scope="{row}">
            <span>{{ row.userName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="房间号" prop="roomNumber" 
        sortable="custom" align="center" width="100" >
          <template slot-scope="{row}">
            <span>{{ row.roomNumber }}</span>
          </template>
        </el-table-column>

        <el-table-column label="费用类别" prop="typeName" 
        sortable="custom" align="center" width="180" >
          <template slot-scope="{row}">
            <span>{{ row.typeName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="金额" prop="typePrice" 
        sortable="custom" align="center" width="100" >
          <template slot-scope="{row}">
            <span>{{ row.typePrice }}</span>
          </template>
        </el-table-column>

        <el-table-column label="缴费月份" prop="typeTime" 
        sortable="custom" align="center" width="120" >
          <template slot-scope="{row}">
            <span>{{ row.typeTime }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="支付方式" prop="paymentMethod" 
        sortable="custom" align="center" width="130" >
          <template slot-scope="{row}">
            <span>{{ row.paymentMethod }}</span>
          </template>
        </el-table-column>

        <el-table-column label="居民缴费时间" prop="chargeDate" 
        sortable="custom" align="center" width="180" >
          <template slot-scope="{row}">
            <span>{{ row.chargeDate }}</span>
          </template>
        </el-table-column>    
        <el-table-column label="状态" prop="isDunned" 
        sortable="custom" align="center" width="180" >
          <template slot-scope="{row}">
            <span>{{ row.isDunned }}</span>
          </template>
        </el-table-column>
        <!--表格内部按钮-->
        <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary"  size="mini" @click="xianxiazhifu(row)">线下支付</el-button>
            <el-button type="primary" size="mini" @click="cuijiao(row)">催缴</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  
      <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
        <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
          <el-table-column prop="key" label="Channel" />
          <el-table-column prop="pv" label="Pv" />
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import dayjs from 'dayjs'; 
  import {findAllroomList,findByPage,zhifu,fetchAllData} from '@/api/costManage'
  import { findAllList} from '@/api/expensetype'
  import waves from '@/directive/waves' // waves directive
  import moment from 'moment'
  import { parseTime } from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  export default {
    name: 'ComplexTable',
    components: { Pagination },
    directives: { waves },
    filters: {
    },
    data() {
      return {
        costList:{
            chargeRecordId:"",
            xianxiazhifu:"线下支付",
            cuijiao:"催缴",
            costTime:dayjs().format('YYYY-MM-DD HH:mm:ss') 
        },
        tableKey: 0,
        list: null,//表格集合数据
        total: 0,//总条数
        listLoading: true,
        listQuery: {//查询的筛选条件
          page: 1,
          limit: 10,
          selectMonth:this.getDefaultYearMonth(),
          roomId:undefined,
          typeId:undefined
        },
        loadAllList:[],
        roomListLoad:[],
        roomListLoading: true,
        typeListLoad:[],
        typeListLoading: true,
        showReviewer: false,
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '修改费用',
          create: '添加费用'
        },
         dialogPvVisible: false,
        pvData: [],
         downloadLoading: false
      }
    },
    created() {//未渲染之前  data加载之后
      this.gettypeList(),
      this.getroomList(),      
      this.getList();
    },
    methods: {
      xianxiazhifu(row) {
        const status = row.isDunned;
      if (status === '已缴费') {
        this.$message({
          message: '已缴费',
          type: 'info',
          duration: 1500,
        });
        return; // 如果是已缴费状态，直接返回，不再执行后续代码
      } 
      this.costList.chargeRecordId = row.chargeRecordId;
      const query = {  
        chargeRecordId: this.costList.chargeRecordId,
        paymentMethod: this.costList.xianxiazhifu, // 支付方式
        costTime: this.costList.costTime, // 当前时间，从costList中获取
      };
      zhifu(query).then(() => {
        this.getList();
              this.$notify({
                title: '成功',
                message: '支付成功',
                type: 'success',
                duration: 2000
              });
            })
          },
    cuijiao(row) {
      const status = row.isDunned;
      if (status === '已缴费') {
        this.$message({
          message: '已缴费',
          type: 'info',
          duration: 1500,
        });
        return; // 如果是已缴费状态，直接返回，不再执行后续代码
      }
      this.costList.chargeRecordId = row.chargeRecordId;
      const query = {
        chargeRecordId: this.costList.chargeRecordId,
        paymentMethod: this.costList.cuijiao, // 支付方式
        costTime: this.costList.costTime, // 当前时间，从costList中获取
      };
      zhifu(query).then(() => {
        this.getList();
              this.$notify({
                title: '成功',
                message: '催缴成功',
                type: 'success',
                duration: 2000
              });
            })
          },
      getList() {//获取 list  total
          this.listLoading = true;
          findByPage(this.listQuery).then(response => {
            this.list = response.data.list
            this.total = response.data.total
            console.log( response.data.list)
                setTimeout(() => {
                  this.listLoading = false
                }, 1.5 * 1000)  
           })         
      }, 
      gettypeList(){
          this.typeListLoading = true;
          findAllList().then(response => {
             this.typeListLoad=response.data
             console.log(this.typeListLoad);
             this.typeListLoading=false;
          })
    },       
    getroomList(){
          this.roomListLoading = true;
          findAllroomList().then(response => {
             this.roomListLoad=response.data
             console.log(this.roomListLoad);
             this.roomListLoading=false;
          })
    },      
      jobSearch() {
        this.getJobListByMonth();
        },
        async initData(data) {
      //获取当前时间
      var now   = new Date();
      var monthn = now.getMonth()+1;
      var yearn  = now.getFullYear();
      this.listQuery.selectMonth = yearn+"-"+monthn;
      this.selectUser = parseInt(sessionStorage.getItem("userid"));
      // this.getWeekJobList({
      //   userid: sessionStorage.getItem("userid"),
      //   weekid: "1"
      // });
        this.getJobListByMonth();
        },
    async getJobListByMonth(data) {
 
    },
    getDefaultYearMonth() {
      // 获取当前年份
      const currentYear = new Date().getFullYear();
      // 获取当前月份（注意：月份是从0开始的，所以需要加1）
      const currentMonth = new Date().getMonth() + 1;
      // 将年份和月份格式化为字符串
      const formattedYear = currentYear.toString();
      const formattedMonth = currentMonth < 10 ? '0' + currentMonth : currentMonth.toString();
      // 组合成默认展示的年月
      return `${formattedYear}-${formattedMonth}`;
    },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          typeId: undefined, 
          typeName: "",
          typePrice:"",
          typeDescription:"",
          typeTime: this.getDefaultYearMonth()
        }
      },
      handleCreate() {
        this.gettypeList();
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
      this.$refs['dataForm'].validate((valid) => {
        //判断验证是否通过
        if (valid) {   
          this.temp.typeTime=this.getDefaultYearMonth();
          addExpenseType(this.temp).then(response => {
            //把当前内容添加到 集合中
          // this.list.unshift(this.temp)
          this.getList();
           //设置是否被不通过
           this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
      handleUpdate(row) {
        const status = row.isDunned;
      if (status === '已缴费') {
        this.$message({
          message: '已缴费',
          type: 'info',
          duration: 1500,
        });
        return; // 如果是已缴费状态，直接返回，不再执行后续代码
      } 
        this.temp = Object.assign({}, row) // copy obj
        this.temp.typeTime = new Date(this.temp.typeTime)
        this.dialogStatus = 'update'
        this.gettypeList();
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },

      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            //临时数据   temp内容拷贝到tempData
            const tempData = Object.assign({}, this.temp)
            //tempData
            tempData.typeTime=moment(String(tempData.typeTime)).format('YYYY-MM')
            updatExpenseType(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              //替换
             // this.list.splice(index, 1, this.temp)
             this.getList();
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDownload() {
      this.downloadLoading = true;
      const query = {};
      fetchAllData(query).then((allData) => {
        this.loadAllList = allData.data.list;
        const tHeader = ['订单编号', '居民ID', '业主姓名', '房间号', '费用类别', '金额', '缴费月份', '支付方式', '居民缴费时间', '状态'];
        const filterVal = ['chargeRecordId', 'userId', 'userName', 'roomNumber', 'typeName', 'typePrice', 'typeTime', 'paymentMethod', 'chargeDate', 'isDunned'];
        const data = this.formatJson(filterVal);
        import('@/vendor/Export2Excel').then(excel => {
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          });
          this.downloadLoading = false;
        });
      });
    },
    formatJson(filterVal) {
      return this.loadAllList.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
      handleCreateType(typeAdd){
        createType(typeAdd).then(() => {
              this.getList();
              this.$notify({
                title: '成功',
                message: '费用类型添加成功',
                type: 'success',
                duration: 2000
              })
            })
      },
      handleFetchPv(pv) {
        
      },

      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }
    }
  }
  </script>
  